package com.woniu.darryringmall.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.woniu.darryringmall.admin.Request.GoodsSpecVO;
import com.woniu.darryringmall.front.entity.GoodsSpec;
import com.woniu.darryringmall.front.service.GoodsSpecService;
import com.woniu.darryringmall.utils.ResponseData;
import com.woniu.darryringmall.utils.ResponseUtils;
import com.woniu.darryringmall.utils.ResultStateCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.List;

@RestController("adminGoodsSpec")
@RequestMapping("admin/goodsSpec")
public class GoodsSpecController {
    @Autowired
    private GoodsSpecService goodsSpecService;

    @RequestMapping("del/{id}")
    public ResponseData del(@PathVariable int id) {
        goodsSpecService.removeById(id);
        return ResponseUtils.SUCCESS;
    }

    @RequestMapping("update")
    public ResponseData update(@RequestBody GoodsSpec goodsSpec) {
        UpdateWrapper<GoodsSpec> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", goodsSpec.getId());
        if (goodsSpec.getStock() != -1) {
            updateWrapper.set("stock", goodsSpec.getStock());
        }
        if (!goodsSpec.getPrice().equals(new BigDecimal("-1"))) {
            updateWrapper.set("price", goodsSpec.getPrice());
        }
        goodsSpecService.update(updateWrapper);

        return ResponseUtils.SUCCESS;
    }

    @RequestMapping("list/{goodsId}")
    public ResponseData list(@PathVariable int goodsId) {
        QueryWrapper<GoodsSpec> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("goodsid", goodsId);
        return ResponseUtils.getResponseData(ResultStateCode.SUCCESS, "操作成功", goodsSpecService.list(queryWrapper));
    }

    @RequestMapping("add")
    public ResponseData add(@RequestBody GoodsSpecVO goodsSpecVO) {
        int goodsId = goodsSpecVO.getGoodsId();
        List<GoodsSpec> goodsSpecs = goodsSpecVO.getGoodsSpecs();
        int count = 0;
        for (GoodsSpec goodsSpec : goodsSpecs) {
            System.out.println(goodsSpec.getSpecValues());
            if (goodsSpecService.getBySpecValues(goodsSpec.getSpecValues(), goodsSpec.getGoodsId()) == null) {
                goodsSpec.setGoodsId(goodsId);
                goodsSpecService.save(goodsSpec);
                count++;
            }
        }
        if (count == 0) {
            return ResponseUtils.FAIL;
        }
        return ResponseUtils.getResponseData(ResultStateCode.SUCCESS,"操作成功", count);
    }
}
